package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sun.org.apache.regexp.internal.RE;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Api(tags = "菜品相关接口")
@RestController
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    DishService dishService;

    /**
     * 新增菜品
     * @param dishDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增菜品")
    public Result saveDish(@RequestBody DishDTO dishDTO){
        String CACHE_KEY = "DISH_"+dishDTO.getCategoryId();
        dishService.saveDishAndFlavors(dishDTO);
        redisTemplate.delete(CACHE_KEY);
        return Result.success();
    }

    /**
     * 分页查询
     * @return
     */
    @ApiOperation("分页查询")
    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        PageResult pageResult = dishService.page(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 根据id删除一条或者多条数据
     * @return
     */
    @ApiOperation("根据id删除一条或者多条数据")
    @DeleteMapping
    public Result delByIds(@RequestParam List<Long> ids){
        //TODO 注意redis的key的特征!!!
        //查询所有相关的KEY DISH_*
        String SEARCH_KEY = "DISH_*";
        Set keys = redisTemplate.keys(SEARCH_KEY);
        //把所有的菜品的缓存全部删除
        redisTemplate.delete(keys);

        dishService.delByIds(ids);
        return Result.success();
    }
}
